"""
基础模型适配器
定义所有模型适配器的通用接口
"""

from abc import ABC, abstractmethod
from typing import Dict, Any, List, Optional
import logging

logger = logging.getLogger(__name__)


class BaseModelAdapter(ABC):
    """基础模型适配器抽象类"""

    def __init__(self, api_key: str, api_url: Optional[str] = None, model: Optional[str] = None):
        self.api_key = api_key
        self.api_url = api_url
        self.model = model

    @abstractmethod
    async def generate_completion(
        self,
        messages: List[Dict[str, str]],
        temperature: float = 0.2,
        max_tokens: int = 4000,
        timeout: float = 300.0,
        **kwargs
    ) -> str:
        """
        生成文本完成

        Args:
            messages: 消息列表，格式为 [{"role": "user", "content": "..."}]
            temperature: 温度参数
            max_tokens: 最大token数
            timeout: 超时时间
            **kwargs: 其他模型特定参数

        Returns:
            生成的文本内容
        """
        pass

    @abstractmethod
    def get_provider_name(self) -> str:
        """获取提供商名称"""
        pass

    @abstractmethod
    def get_supported_models(self) -> List[str]:
        """获取支持的模型列表"""
        pass

    def validate_config(self) -> bool:
        """验证配置是否有效"""
        if not self.api_key:
            logger.error(f"{self.get_provider_name()} API密钥未配置")
            return False

        # 检查是否是占位符密钥
        placeholder_patterns = [
            "your-api-key-here",
            "your-deepseek-api-key-here",
            "your-openai-api-key-here",
            "your-gemini-api-key-here",
            "your-doubao-api-key-here",
            "your-claude-api-key-here",
            "sk-xxxxxxxxxxxxxxxx",
            "AIxxxxxxxxxxxxxxxx"
        ]

        if self.api_key in placeholder_patterns:
            logger.error(f"{self.get_provider_name()} API密钥是占位符，请配置真实的API密钥")
            return False

        # 检查密钥长度（大多数API密钥都有最小长度要求）
        if len(self.api_key) < 10:
            logger.error(f"{self.get_provider_name()} API密钥长度过短，请检查配置")
            return False

        return True

    def format_error_message(self, error: Exception) -> str:
        """格式化错误消息"""
        return f"{self.get_provider_name()} API调用失败: {str(error)}"
